var core = require('core');
var util = core.util;
var wechat = core.wechat;
var send = core.send;
var get = function(req, res, next){
    var query = req.query;
    var state = query.state;
    var errcode = query.errcode;
    var token = query.token;
    var code = query.code;

    if(!state && !errcode && !token)
        res.redirect("https://open.weixin.qq.com/connect/oauth2/authorize?appid="+ wechat.config.AppID +"&redirect_uri="+ wechat.config.URL+"admin/home&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect");
    else if(!errcode && code && !token){
        var param = {
            appid : wechat.config.AppID,
            secret : wechat.config.AppSecret,
            code : query.code,
            grant_type : 'authorization_code'
        };
        wechat.api.get('sns/oauth2/access_token', param, function(err, body){
            if(err)
                return res.redirect(wechat.config.URL+"error?errcode=100001");
            core.api("user/getUser", { openid: body.openid, tagid_list: wechat.config.tagid_contrast[1] }, function(err, doc){
                if((doc.code && doc.code != 100201) || err){
                    return res.redirect(wechat.config.URL+"error?errcode=200000");
                }else if(!doc.docs){
                    return next();
                }
                core.api("open/setToken", {openid: body.openid, oid: body.openid}, function(err, doc){
                    if(err || doc.code){
                        return res.redirect(wechat.config.URL+"error?errcode=300001");
                    };
                    return res.redirect(wechat.config.URL+"admin/home?token="+ doc.docs.token +"#home");
                });
            });
        });
    }else if(token){
        core.api("open/getToken", {token: token, type: "TempToken"}, function(err, doc){
            if(err || doc.code){
                return res.redirect(wechat.config.URL+"error?errcode=200000");
            };
            var SEND = new send(0);
            SEND.docs = {
                token : token,
                jssdk : wechat.getJSSDK(req.originalUrl)
            };
            res.render("admin/home", SEND);
        });

    }else if(errcode){
        var err = new send(errcode);
        err.docs = {
            jssdk : wechat.getJSSDK(req.originalUrl)
        };
        res.render("admin/home", err);
    }
};

module.exports = get;
